package com.bobamrz.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.bobamrz.db.ConnectionManager;
import com.bobamrz.domain.UserDTO;

public class UserDAO {
	
	private Logger log = Logger.getLogger(UserDAO.class);

	public static final String AUTH_SQL = 
			"SELECT * FROM auth(?, ?);";
	private PreparedStatement authStatement;
	private Connection connection = ConnectionManager.getConnection();
	
	public UserDTO authFunction(String password, String username) {
		try {
			log.debug("retreiving user");
			authStatement = connection.prepareStatement(AUTH_SQL);
			authStatement.setString(1, username);
			authStatement.setString(2, password);
			
			ResultSet resultSet = authStatement.executeQuery();
			if(resultSet.next()) {
				log.debug("user found");
				UserDTO user = new UserDTO();
				user.setEmployeeId(resultSet.getLong("employee"));
				user.setFirstname(resultSet.getString("first_name"));
				user.setLastname(resultSet.getString("last_name"));
				user.setUserAccountId(resultSet.getLong("account"));
				return user;
			} else {
				log.debug("user not found");
				return null;
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
	}
	
}
